<?php

namespace app\curd\command;

use think\admin\Command;
use think\console\Input;
use think\console\Output;

use think\console\input\Argument;
use think\helper\Str;
use think\admin\extend\CodeExtend;
use think\admin\service\QueueService;

class DdSql extends Command
{
	protected $appPath;
	protected $type = "Sql";

	public function __construct()
	{
		$this->appPath = app_path();
		parent::__construct();
		$this->setDescription("生成数据库模板表(仅支持mysql数据库)");
	}

	protected function configure()
	{
		$this->setName('xcurd:sql')
			->addArgument('app', Argument::REQUIRED, "The app of the sql")
			->addArgument('module', Argument::REQUIRED, "The module of the sql")
			->addArgument('desc', Argument::REQUIRED, "The desc of the sql")
			->setDescription('Create a new sql');
	}

	protected function execute(Input $input, Output $output)
	{
		$app = trim($input->getArgument('app'));

		$module = trim($input->getArgument('module'));

		$desc = trim($input->getArgument('desc'));

		$sql_file = $this->makeSql($app, $module, $desc);

		$output->writeln('<info>' . $sql_file . ' created successfully.</info>');
	}

	protected function getPathName(): string
	{
		return $this->app->getRootPath() . 'database' . DIRECTORY_SEPARATOR . 'migrations' . DIRECTORY_SEPARATOR;
	}

	// 创建模板
	public function makeSql($app, $module, $desc)
	{
		// 创建模板路径
		$viewPath = $this->getPathName();
		if (!is_dir($viewPath)) {
			mkdir($viewPath, 0777, true);
		}

		// 模板源文件
		$stubPath = $this->appPath . 'curd' . DIRECTORY_SEPARATOR . 'command' . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'InstallDd6Module.php';
		// 文件内容替换
		$stub = str_replace(
			[
				'Dd6',
				'dd6',
				'Module',
				'module',
				'数据管理',
			],
			[
				Str::studly($app),
				$app,
				Str::studly($module),
				$module,
				$desc,
			],
			file_get_contents($stubPath)
		);

		// 创建文件
		$sql_file = CodeExtend::uniqidDate(14) . '_install_' . $app . '_' . $module;
		file_put_contents($viewPath . DIRECTORY_SEPARATOR . $sql_file . '.php', $stub);

		// 执行数据库脚本
		QueueService::instance()->register('执行数据库脚本', "migrate:run");

		return $sql_file;
	}
}
